package email

import (
	"gf_email_task/app/model/davel_email_appid"
	"gf_email_task/app/model/davel_email_system"
	"gf_email_task/app/model/davel_email_task"
	"gf_email_task/app/model/davel_email_template"
	"errors"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
	"github.com/gogf/gf/util/grand"
)

//发送邮件任务
func EmailService(param *EmailServiceParam) error {
	emailAppidEntity := davel_email_appid.GetEmailAppid(param.Appid,param.Token)
	if emailAppidEntity==nil {
		return errors.New("appid deny")
	}

	//获取发送模板
	emailTemplateEntity := davel_email_template.GetEmailTemplate(param.TemplateId)
	if emailTemplateEntity == nil {
		return errors.New("template not exists")
	}

	//记录邮件任务
	if !davel_email_task.CheckEmailTaskLimit(param.Email) {
		return errors.New("to fast")
	}

	//记录邮件任务
	emailTaskId,err := davel_email_task.AddEmailTask(param.Email,emailAppidEntity.Id,emailTemplateEntity.Id,param.Param1,param.Param2,param.Param3)
	if err != nil {
		return err
	}

	replaceStr := []string{
		"{logo}" , emailAppidEntity.Logo,
		"{siteName}", emailAppidEntity.SiteName,
		"{param1}", param.Param1,
		"{param2}", param.Param2,
		"{param3}", param.Param3,
	}
	emailTemplateEntity.Title = gstr.ReplaceByArray(emailTemplateEntity.Title,replaceStr)
	emailTemplateEntity.Content = gstr.ReplaceByArray(emailTemplateEntity.Content,replaceStr)
	//增加随机值
	emailTemplateEntity.Content += "<div style='display: none' class='random'>" + grand.Letters(16) + "</div>"
	//增加访问回调
	emailTemplateEntity.Content += "<img style='display: none' src='http://"+ param.Host +"/email/logo?eid=" + gconv.String(emailTaskId) + "'>"

	//加入发送邮件队列
	go davel_email_system.EmailSystemQuenePush(davel_email_system.EmailSystemQueneParam{
		ToEmail: param.Email,
		Title: emailTemplateEntity.Title,
		Content: emailTemplateEntity.Content,
		EmailTaskId : emailTaskId,
		FromName: emailAppidEntity.SiteName,
	})

	return nil
}

//发送邮件任务
func EmailViewService(param *EmailViewParam) error {
	_,err := davel_email_task.ViewEmailTask(param.Eid)
	if err != nil {
		return err
	}
	return nil
}

//发送邮件任务
func EmailTemplateService() ([]*davel_email_template.Entity,error) {
	res := davel_email_template.GetAllTemplate()
	if res == nil {
		return nil,errors.New("not data")
	}
	return res,nil
}